/* 
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

var suload = false;
var storage = window.localStorage;
var shoproot = '/wshop/';

//Spinner 配置项
var Spinner = new Spinner({
    lines: 11, // The number of lines to draw
    length: 8, // The length of each line
    width: 3, // The line thickness
    radius: 8, // The radius of the inner circle
    corners: 0.9, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: '#000', // #rgb or #rrggbb or array of colors
    speed: 1, // Rounds per second
    trail: 25, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: true, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: 'auto', // Top position relative to parent
    left: 'auto' // Left position relative to parent
});

$(function() {
    // window resize listener
    resize();
    window.onresize = resize;

    if ($('#slider').length > 0 && $('.slider').length > 1) {
        // slider
        window.currentTab = 0;
        $('#slider').bind({
            'touchstart mousedown': function(event) {
                // touch start
                // event.preventDefault();
                if (event.originalEvent.touches)
                    event = event.originalEvent.touches[0];
                window.touchStartX = event.clientX;
                window.touchStartY = event.clientY;
                window.touchStartOffsetX = parseInt($('.slider').eq(0).css('marginLeft'));
                window.touchEndOffsetX = 0;
                window.touchTabLength = $('.slider').length - 1;
            },
            'touchmove mousemove': function(event) {
                // touch move
                if (window.touchStartX && window.touchStartY) {
                    event.preventDefault();
                    if (event.originalEvent.touches)
                        event = event.originalEvent.touches[0];
                    touchX = event.clientX;
                    touchY = event.clientY;
                    touchEndOffsetX = touchStartOffsetX - (touchStartX - touchX);
                    // movement
                    $('.slider').eq(0).css('marginLeft', touchEndOffsetX + 'px');
                }
            },
            'touchend touchcancel mouseup': function(event) {
                // event.preventDefault();
                if (Math.abs(touchX - touchStartX) < 10) {
                    // 横向太低
                    goSlider(0);
                } else {
                    var right = (touchX - touchStartX) > 0;
                    goSlider(right);
                }
                // gc
                touchStartY = null;
                touchStartX = null;
            }
        });
    }

    // orderlist列表页面
    if ($('#uc-orderlist').length > 0) {
        window.currentOrderpage = 0;
        window.orderLoading = false;
        // init list
        loadOrderList(currentOrderpage);
        // onscroll bottom
        $(window).scroll(function() {
            totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
            if ($(document).height() <= totalheight && !orderLoading) {
                //加载数据
                loadOrderList(++currentOrderpage);
            }
        });
    }

    var touchStarget = null;

    // 链接点击效果
    $('[data-swclass]').each(function(index, node) {
        var swclass = $(node).attr('data-swclass');
        var link = $(node).attr('data-link');
        $(node).bind({
            'touchstart mousedown': function(event) {
                if (event.originalEvent.touches)
                    event = event.originalEvent.touches[0];
                $(node).addClass(swclass);
                touchStarget = event.target;
            },
            'touchend mouseup': function(event) {
                $(node).removeClass(swclass);
                if (event.originalEvent.touches)
                    event = event.originalEvent.touches[0];
                if (event.target === touchStarget) {
                    if (link) {
                        if (/javascript/.test(link)) {
                            link = link.replace('javascript:', '');
                            eval(link);
                        } else {
                            location.href = link;
                        }
                    }
                }
                event.preventDefault();
            }
        });
    });

    $('.bottom_nav a').hover(function() {
        $(this).find('i').toggleClass('hover');
    }, function() {
        $(this).find('i').toggleClass('hover');
    });


    // 数量选择按钮
    $('#productCountMinus').bind({
        'touchend touchcancel mouseup': function(event) {
            event.preventDefault();
            var node = $('#productCountNumi');
            node.val(parseInt(node.val()) === 1 ? 1 : node.val() - 1);
        }
    });
    $('#productCountPlus').bind({
        'touchend touchcancel mouseup': function(event) {
            event.preventDefault();
            var node = $('#productCountNumi');
            node.val(parseInt(node.val()) + 1);
        }
    });


});

// resizer
function resize() {
    $('.nav-round').each(function() {
        $(this).height($(this).width());
    });
    $('.sliderTip').each(function() {
        $(this).css('left', ($(this).parent().width() - this.clientWidth) / 2);
    });
    var w = $('.productIW').width();
    $('.productIW').height(w);
}

// slider transmate
function goSlider(Right) {
    Right = Right === 0 ? 0 : (Right === true ? -1 : 1);
    currentTab += Right;
    currentTab = currentTab < 0 ? 0 : currentTab > touchTabLength ? touchTabLength : currentTab;
    var sliderWidth = $('.slider').eq(0).width();
    var finalOffsetX = -currentTab * sliderWidth;
    $('.slider').eq(0).animate({'marginLeft': finalOffsetX + 'px'});
    $('.sliderTipItems.current').removeClass('current');
    $('.sliderTipItems').eq(currentTab).addClass('current');
}

Object.onew = function(o) {
    var F = function(o) {
    };
    F.prototype = o;
    return new F;
};

// processing animation block
var Processing = Object.onew({
    start: function() {
        var node = $("<div class='processing'></div>");
        node.css({top: (($(body).height() - node.height()) / 2), left: (($(body).width() - node.width()) / 2)});
        $('body').append("<div class='processing'></div>");
    },
    finish: function() {
        $('.processing').remove();
    }
});

/**
 * loading animate
 * @type @exp;Object@call;onew
 */
var Loading = Object.onew({
    start: function(id) {
        Spinner.spin($(id).get(0));
    },
    finish: function() {
        $('.pageNot').each(function(i, node) {
            $(node).css('line-height', $(node).height() + 'px');
        });
        Spinner.spin().stop();
    }
});

var Tiping = Object.onew({
    flas: function(content) {
        var width = 120;
        var height = 60;
        var node = $("<div class='_Tiping'>" + content + "</div>");
        $('body').append(node);
        node.css({
            left: (document.body.clientWidth - width) / 2,
            top: ($(window).height() - height) / 2,
            width: width,
            height: height,
            lineHeight: height + 'px'
        });
        setInterval(function() {
            $('._Tiping').fadeOut(800);
        }, 1000);
    }
});

// 购物车对象
var Cart = Object.onew({
    cart: {},
    init: function() {
        var _d = storage.getItem('cart');
        if (_d) {
            this.cart = eval('(' + storage.getItem('cart') + ')');
        } else {
            this.cart = {};
        }
    },
    add: function(productId, count) {
        eval("var ext = this.cart.p" + productId);
        if (ext) {
            eval("this.cart.p" + productId + "+=" + count);
        } else {
            eval("this.cart.p" + productId + "=" + count);
        }
        this.save();
    },
    del: function(productId) {
        eval("delete this.cart.p" + productId);
        this.save();
    },
    clear: function() {
        this.cart = {};
        storage.setItem('cart', '{}');
        storage.removeItem('tmporder');
        storage.removeItem('carthash');
    },
    save: function() {
        storage.setItem('cart', $.toJSON(this.cart));
    }
});

Cart.init();
/**
 * 订单操作对象
 * @type @exp;Object@call;onew
 */
var Orders = Object.onew({
    /**
     * 确认收货
     * @returns {boolean}
     */
    confirmExpress: function(orderId) {
        orderId = parseInt(orderId);
        if (orderId > 0) {
            if (confirm('你确认收到货品了吗?')) {
                $.post('?/Order/confirmExpress', {orderId: orderId}, function(res) {
                    res = parseInt(res);
                    if (res > 0) {
                        $('#orderitem' + orderId).slideUp();
                        if ($('#expresscode')) {
                            window.location.reload();
                        }
                    } else {
                        alert('确认收货失败！');
                        bugNotify('确认收货失败！');
                    }
                });
            }
        }
    },
    /**
     * 取消订单
     * @returns {boolean}
     */
    cancelOrder: function(orderId, node) {
        orderId = parseInt(orderId);
        if (orderId > 0) {
            if (confirm('你确认要取消订单吗?')) {
                $.post('?/Order/cancelOrder', {
                    orderId: orderId
                }, function(res) {
                    if (res === "1") {
                        $(node).parent().parent().slideUp();
                    } else {
                        alert('订单取消失败！');
                        bugNotify(orderId + '订单取消失败！服务器返回' + res);
                    }
                });
            }
        }
    },
    /**
     * 微信支付
     * @returns {undefined}
     */
    wepay: function(orderId) {
        orderId = parseInt(orderId);
        if (orderId > 0) {

        }
    },
    /**
     * 
     * @param {type} 评价
     * @returns {undefined}
     */
    comment: function(orderId) {
        orderId = parseInt(orderId);
        if (orderId > 0) {

        }
    }
});

/**
 * 关注公众号提示
 * @returns {undefined}
 */
function addContact() {

}

// Ajax load product list 
function loadProductList(page) {
    // params
    var searchKey = $('#searchBox').val();
    // request uri
    var _url = '?/vProduct/ajaxProductList/page=' + parseInt(page) + '&searchKey=' + encodeURI(searchKey) + '&cat=' + $('#cat').val() + '&orderby=' + $('#orderby').val()
    listLoading = true;
    Loading.start("#loading-wrap");
    $.get(_url, function(HTML) {
        if (HTML === '0' && searchKey !== '' && !suload) {
            // nothing
            var h = $(window).height() - $('#product_list')[0].offsetTop - 45;
            $("#product_list").html('<div id="productlistNothing" onclick="location=\'/wshop/\'"></div>');
            $('#loading-wrap').remove();
            $('#productlistNothing').css({
                height: h
            });
        } else if (HTML !== '0') {
            // list
            suload = true;
            $("#product_list").append(HTML);
            var w = $('.productIW').width();
            $('.productIW').height(w);
        }
        listLoading = false;
        Loading.finish();
        searchKey = null;
        _url = null;
    });
}

// Ajax load Order list 
function loadOrderList(page) {
    page = parseInt(page);
    console.log(page);
    if (page === -1) {
        page = 0;
        $("#uc-orderlist").html('');
    }
    // request uri
    var _url = '?/Uc/ajaxOrderlist/page=' + page + '&status=' + $('#status').val()
    orderLoading = true;
    Loading.start("#loading-wrap");
    $.get(_url, function(HTML) {
        if (page == 0) {
            $("#uc-orderlist").html(HTML);
        } else {
            $("#uc-orderlist").append(HTML);
        }
        orderLoading = false;
        Loading.finish();
        _url = null;
    });
}

/**
 * 
 * @returns {undefined}
 */
function addToCart() {
    var productId = parseInt($('#iproductId').val());
    var count = parseInt($('#productCountNumi').val());
    Cart.add(productId, count);
    Tiping.flas('已经加入购物车');
}

/**
 * 
 * @param {type} form
 * @returns {undefined}
 */
function searchdo(form) {
    var inp = $('input[type=search]', form);
    if (inp.val() === '')
        return;
    var target = inp.attr('targ');
    target = encodeURI(target + '&searchkey=' + inp.val());
    window.location.href = 'http://' + document.domain +
            (window.location.port ? ':' + window.location.port : '') + window.location.pathname + '?/' + target;
}

/**
 * Uchome
 * @returns {undefined}
 */
function UchomeLoad() {
    // WeixinJSBridge.call('hideOptionMenu');
}

/**
 * Objcount
 * @param {type} o
 * @returns {Number|Boolean}
 */
function CartCount(o) {
    var sum = 0;
    for (var k in o) {
        sum += o[k];
    }
    return sum;
}

/**
 * ExpressDetailOnload
 * @returns {undefined}
 */
function ExpressDetailOnload() {
    Loading.start("#loading-wrap", 200);
    $.post('?/Order/ajaxGetExpressDetails', {
        com: $('#expresscom').val(), nu: $('#expresscode').val()
    }, function(res) {
        res = res.replace(/\d{4}-0?/g, '');
        $('#express-dt').html(res);
//        var offsetStart = '<li><strong>查询结果如下所示：</strong></li>';
//        var offsetEnd = '</form>';
//        res = res.replace('<!DOCTYPE HTML>', '');
//        $('#express-dt').html(res.substring(res.indexOf(offsetStart) + offsetStart.length, res.indexOf(offsetEnd)));
        $('#loading-wrap').remove();
        Loading.finish();
    });
}

/**
 * 查看商品onload
 * @returns {undefined}
 */
function viewproductOnload() {
    // 商品首图自动高度
    var _h = $('#slider').eq(0).width();
    $('#slider').height(_h);
    $('.slider').height(_h);
    $.cookie('vproductheight', _h);
    // 图片加载失败自动删除，不显示白块
    $("#content img").bind("error", function() {
        $(this).remove();
    });

    // 自定义分享
    var comId = $('#comid').val();
    var productId = parseInt($('#iproductId').val());
    var imgUrl = $('#shareimg').val();
    var lineLink = "http://112.124.44.172/wshop/?/vProduct/view/id=" + productId + "&showwxpaytitle=1&com=" + comId;
    var descContent = '';
    var shareTitle = $('#sharetitle').val();

    WeixinJSBridge.on('menu:share:timeline', function(argv) {
        WeixinJSBridge.invoke('shareTimeline', {
            "img_url": imgUrl,
            "img_width": "300",
            "img_height": "300",
            "link": lineLink,
            "desc": descContent,
            "title": shareTitle
        }, function() {
            pvShareCallback(productId, comId);
        });
    });
    WeixinJSBridge.on('menu:share:appmessage', function(argv) {
        WeixinJSBridge.invoke('sendAppMessage', {
            "appid": $.cookie('appid'),
            "img_url": imgUrl,
            "img_width": "300",
            "img_height": "300",
            "link": lineLink,
            "desc": "全球高端母婴名品汇，为妈妈收罗天下名品。",
            "title": shareTitle
        }, function() {
            pvShareCallback(productId, comId);
        });
    });
    // 分享到微博
    WeixinJSBridge.on('menu:share:weibo', function(argv) {
        WeixinJSBridge.invoke('shareWeibo', {
            "content": descContent,
            "url": lineLink
        }, function() {
            pvShareCallback(productId, comId);
        });
    });
    WeixinJSBridge.call('showOptionMenu');
}

/**
 * 商品分享记录
 * @param {type} productId
 * @param {type} comId
 * @returns {undefined}
 */
function pvShareCallback(productId, comId) {
    $.post("?/Company/addComSpread", {
        productId: productId,
        comId: comId
    }, function(res) {
    });
}

/**
 * 首页onload
 * @returns {undefined}
 */
function homeOnload() {
    WeixinJSBridge.call('showOptionMenu');
    WeixinJSBridge.on('menu:share:timeline', function(argv) {
        WeixinJSBridge.invoke('shareTimeline', {
            "img_url": "http://112.124.44.172/wshop/static/images/logo-source.jpg",
            "img_width": "200",
            "img_height": "200",
            "link": "http://112.124.44.172/wshop/?/Index/index/" + 'com=' + $.cookie('uopenid'),
            "desc": "熹贝母婴用品",
            "title": "全球高端母婴名品汇，为妈妈收罗天下名品。"
        }, function(arg) {

        });
    });
    WeixinJSBridge.on('menu:share:appmessage', function(argv) {
        WeixinJSBridge.invoke('sendAppMessage', {
            "appid": $.cookie('appid'),
            "img_url": "http://112.124.44.172/wshop/static/images/logo-source.jpg",
            "img_width": "300",
            "img_height": "300",
            "link": "http://112.124.44.172/wshop/?/Index/index/" + 'com=' + $.cookie('uopenid'),
            "desc": "全球高端母婴名品汇，为妈妈收罗天下名品。",
            "title": "熹贝母婴用品"
        }, function(arg) {

        });
    });
}

function pvListOnload() {
    // 初始化加载列表
    if ($('#product_list').length > 0 && $('#orderDetailsWrapper').length !== 1) {
        window.currentPrudctpage = 0;
        window.listLoading = false;
        // init list
        loadProductList(currentPrudctpage);
        // onscroll bottom
        $(window).scroll(function() {
            totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
            if ($(document).height() <= totalheight && !listLoading) {
                //加载数据
                loadProductList(++currentPrudctpage);
            }
        });
    }

    // subnav
    $('.subnav').click(function() {
        var orderby = $(this).attr('orderby');
        $('.active').removeClass('active');
        window.currentPrudctpage = 0;
        var priceB = $(this).find('b._priceB');
        $(this).addClass('active');
        $(this).find('b._priceB').toggleClass('up');
        if (priceB.length !== 0) {
            orderby += priceB.hasClass('up') ? " DESC" : " ASC";
        } else {
            orderby += " DESC";
        }
        $('#orderby').val(orderby);
        $('#product_list').html("");
        if (!window.dontload)
            loadProductList(0);
        window.dontload = false;
    });
    window.dontload = true;
    if ($('#orderby').val() === '`sale_count`') {
    } else {
        $('.subnav').eq(0).click();
    }

    WeixinJSBridge.on('menu:share:timeline', function(argv) {
        WeixinJSBridge.invoke('shareTimeline', {
            "img_url": "http://112.124.44.172/wshop/static/images/logo-source.jpg",
            "img_width": "200",
            "img_height": "200",
            "link": window.location.href + '&com=' + $.cookie('uopenid'),
            "desc": "熹贝母婴用品",
            "title": "全球高端母婴名品汇，为妈妈收罗天下名品。"
        }, function(arg) {

        });
    });
    WeixinJSBridge.on('menu:share:appmessage', function(argv) {
        WeixinJSBridge.invoke('sendAppMessage', {
            "appid": $.cookie('appid'),
            "img_url": "http://112.124.44.172/wshop/static/images/logo-source.jpg",
            "img_width": "300",
            "img_height": "300",
            "link": window.location.href + '&com=' + $.cookie('uopenid'),
            "desc": "全球高端母婴名品汇，为妈妈收罗天下名品。",
            "title": "熹贝母婴用品"
        }, function(arg) {

        });
    });
    // product列表页面
    WeixinJSBridge.call('showOptionMenu');
}

/**
 * notify bug to admin
 * @param {string} message
 * @returns {undefined}
 */
function bugNotify(message) {
    $.post('?/Notify/notifyBug', {message: message}, function() {

    });
}

/**
 * spreadListOnload
 * @returns {undefined}
 */
function spreadListOnload() {
    window.spreadListPage = 0;
    // init loader
    ajaxLoadSpreadList(spreadListPage);
    // scroll loader
    $(window).scroll(function() {
        ajaxLoadSpreadList(++spreadListPage);
    });
}

/**
 * 
 * @param {int} page
 * @returns {undefined}
 */
function ajaxLoadSpreadList(page) {
    var requestUrl = "?/Uc/ajaxSpreadList/page=" + page;
    Loading.start("#loading-wrap");
    $.get(requestUrl, function(res) {
        Loading.finish();
        $('#uc-spreadlist').append(res);
    });
    requestUrl = null;
}

function debug(va) {
    console.log(va);
}

function hGoback() {
    if (window.history.length > 0) {
        window.history.go(-1);
    } else {
        window.href = shoproot;
    }
}

function adminTest() {
    $.cookie('uid', 100244);
    $.cookie('uopenid', 'od2ZEuGcj5xSuk_YJuSpJ2wPsKp0');
}

function hGohome() {
    window.location.href = shoproot;
}